package io.acna.qiniu.core;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

import static io.acna.qiniu.core.Params.*;

import java.io.File;

/**
 * Created by wscl on 2015/6/7.
 */
public class Main {
    UploadManager uploadManager = new UploadManager();
    public static Auth auth = Auth.create(Key.ACCESS_KEY, Key.SECRET_KEY);
    static String token = null;

    public static void main(String[] args) {
        Params.init(args);
        if (BUCKET != null)
            token = auth.uploadToken(BUCKET);
        else
            token = auth.uploadToken(Key.BUCKET);
        File file = null;
        Main main = new Main();
        boolean flag = false;
        for (String fn : DirUtils.listFile(RESOURCES_PATH)) {
            file = new File(fn);
            if (CONTINUE_FILE != null && !"none".equals(CONTINUE_FILE)) {
                if (fn.indexOf(CONTINUE_FILE) != -1) {
                    flag = true;
                    continue;
                }
                if (!flag)
                    continue;
            }
            System.out.print("正在上传：" + fn);
            try {
                main.uploadFile(file, FileKeyUtils.pathAmend(fn, RESOURCES_PATH), token);
                System.out.print("_SUCCESS!");
            } catch (QiniuException e) {
                token = auth.uploadToken(Key.BUCKET);
                try {
                    main.uploadFile(file, FileKeyUtils.pathAmend(fn, RESOURCES_PATH), token);
                } catch (QiniuException e1) {
                    System.out.println("非token错误导致的上传失败!");
                    e1.printStackTrace();
                }
            }
            System.out.println();
        }
    }


    public void uploadFile(File file, String key, String upToken) throws QiniuException {
        Response res = uploadManager.put(file, key, upToken);
    }
}
